package com.my.swas.sso.module.admin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.my.swas.common.utils.BeanCopierUtil;
import com.my.swas.common.utils.RedisUtil;
import com.my.swas.common.constans.CommConst;
import com.my.swas.sso.module.admin.entity.Dict;
import com.my.swas.sso.module.admin.mapper.DictMapper;
import com.my.swas.sso.module.admin.service.DictService;
import com.my.swas.sso.module.admin.vo.DictTreeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description:
 * @author: :MaYong
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Autowired
    RedisUtil redisUtil;

    @Override
    public Map<String, List<DictTreeVo>> initDict() {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(Dict::getStatus, CommConst.ONE);
        List<Dict> dictList = baseMapper.selectList(queryWrapper);
        Map<String, List<DictTreeVo>> stringListMap = Maps.newConcurrentMap();
        for (Dict dict : dictList) {
            if (null == dict.getParentId()) {
                List<DictTreeVo> dictTreeVoList = buildDictTree(dictList, dict.getId());
                stringListMap.put(dict.getCode(), dictTreeVoList);
                if (CollectionUtil.isNotEmpty(dictTreeVoList)) {
                    redisUtil.lRightPushAll(dict.getCode(), dictTreeVoList);
                }
            }
        }
        return stringListMap;
    }

    /**
     * 递归组装字段对象
     *
     * @return
     */
    private List<DictTreeVo> buildDictTree(List<Dict> dictList, Long dictId) {
        List<DictTreeVo> dictTreeVoList = Lists.newArrayList();
        List<Dict> dicts = dictList.stream().filter(dict -> dictId.equals(dict.getParentId())).collect(Collectors.toList());
        DictTreeVo dictTreeVo = null;
        for (Dict dict : dicts) {
            dictTreeVo = new DictTreeVo();
            BeanCopierUtil.convert(dict, dictTreeVo);
            dictTreeVo.setDictTreeVoList(buildDictTree(dictList, dict.getId()));
            dictTreeVoList.add(dictTreeVo);
        }
        return dictTreeVoList;
    }
}
